package com.atguigu.gmall.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.func.DimSinkFunction;
import com.atguigu.gmall.realtime.app.func.TableProcessFunction;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import com.atguigu.gmall.realtime.utils.HbaseUtil;
import com.atguigu.gmall.realtime.utils.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.runtime.state.storage.JobManagerCheckpointStorage;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;

/**
 * @author Felix
 * @date 2023/9/24
 * DIM维度层处理
 * 需要启动的进程
 *      zk、kafka、maxwell、hdfs、hbase、DimApp
 * 开发流程
 *      基本环境准备
 *      检查点相关的设置
 *      从kafka主题中读取业务数据
 *          MyKafkaUtil-getKafkaSource()
 *      对读取的数据进行类型转换并进行简单的ETL    jsonStr->jsonObj
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~读取业务数据~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *      使用FlinkCDC读取配置表中配置信息
 *          -创建MySqlSource对象
 *          -读取数据 封装为流
 *      对读取的配置流数据进行类型转换 jsonStr->TableProcess
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~读取配置数据~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *      根据读取的配置信息到hbase中建表或者删除表
 *      将配置流进行广播---broadcast(广播状态描述器)
 *      将主流业务数据与广播流配置信息进行广联---connect
 *      对关联之后的数据进行处理---process
 *          class TableProcessFunction extends BroadcastProcessFunction{
 *              open:将配置表中的配置信息预加载到广播状态中
 *              processElement:处理主流业务数据
 *                  根据处理的表名到广播状态以及configMap中获取对应的配置信息，如果配置信息不为空，说明是维度
 *                  将维度数据data内容传递到下游
 *                      过滤掉不需要传递的属性
 *                      补充操作类型
 *                      补充当前维度对应的配置信息
 *              processBroadcastElement:处理广播流数据
 *                  op=="d"
 *                      从广播状态以及configMap中删除对应的配置信息
 *                  op!="d"
 *                      向广播状态以及configMap中put对应的配置信息
 *          }
 *      将维度数据写到hbase表中
 *          class DimSinkFunction extends RichSinkFunction{
 *              invoke:
 *                  type == "delete"
 *                      从hbase表中删除对应的记录
 *                  type != "delete"
 *                      向hbase表中put一条数据
 *          }
 *      关于HbaseUtil中提供的方法
 *          获取连接
 *          关闭连接
 *          删表
 *          建表
 *          删除表中记录
 *          向表中put数据
 *
 * 程序执行流程（以对业务数据库中品牌维度表进行修改操作为例）
 *      当DimApp应用程序启动的时候，会将配置表中的配置信息加载到程序中(configMap、广播状态)
 *      当修改了品牌表中的一条数据后，binlog会将变化记录下来
 *      maxwell会从binlog中读取变化并封装为json字符串发送到kafka的topic_db主题中
 *      DimApp从kafka主题中将数据读取出来，并进行类型的转换
 *      DimApp会将主流读取到的业务数据和广播流中的配置信息进行关联
 *      对读取的主流数据进行处理
 *          根据表名判断是不是维度，如果是维度数据，将维度数据传递到下游
 *      将维度流数据写到hbase对应的表中
 */
public class DimApp {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        /*//TODO 2.检查点相关的设置
        //2.1 开启检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        //2.7 设置操作hadoop的用户
        System.setProperty("HADOOP_USER_NAME","atguigu");*/
        //TODO 3.从kafka主题中读取业务数据
        //3.1 声明消费的主题以及消费者组
        String topic = "topic_db";
        String groupId = "dim_app_group";
        //3.2 创建消费者对象
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaStrDS
            = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "Kafka Source");

        //TODO 4.对读取的数据进行类型转换并进行简单的ETL  jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
            new ProcessFunction<String, JSONObject>() {
                @Override
                public void processElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
                    try {
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        String type = jsonObj.getString("type");
                        if (!"bootstrap-start".equals(type) && !"bootstrap-complete".equals(type)) {
                            out.collect(jsonObj);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );
        // jsonObjDS.print(">>>>");

        //TODO 5.使用FlinkCDC读取配置表中配置信息
        //5.1 创建MySqlSource
        Properties props = new Properties();
        props.setProperty("useSSL", "false");
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
            .hostname("hadoop102")
            .port(3306)
            .databaseList("gmall0417_config") // set captured database
            .tableList("gmall0417_config.table_process_dim") // set captured table
            .username("root")
            .password("123456")
            .jdbcProperties(props)
            .serverTimeZone("Asia/Shanghai")
            .deserializer(new JsonDebeziumDeserializationSchema())
            .startupOptions(StartupOptions.initial())
            .build();

        //5.2 读取数据 封装为流
        //"op":"r": {"before":null,"after":{"source_table":"user_info","sink_table":"dim_user_info","sink_family":"info","sink_columns":"id,login_name,name,user_level,birthday,gender,create_time,operate_time","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0417_config","sequence":null,"table":"table_process_dim","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1695539055170,"transaction":null}
        //"op":"c": {"before":null,"after":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1695539123000,"snapshot":"false","db":"gmall0417_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11368309,"row":0,"thread":null,"query":null},"op":"c","ts_ms":1695539123216,"transaction":null}
        //"op":"u": {"before":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"after":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1695539150000,"snapshot":"false","db":"gmall0417_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11368669,"row":0,"thread":null,"query":null},"op":"u","ts_ms":1695539150100,"transaction":null}
        //"op":"d": {"before":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"after":null,"source":{"version":"1.6.4.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1695539176000,"snapshot":"false","db":"gmall0417_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000003","pos":11369055,"row":0,"thread":null,"query":null},"op":"d","ts_ms":1695539176056,"transaction":null}
        DataStreamSource<String> mySqlStrDS
            = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");
        // mySqlStrDS.print(">>");

        //TODO 6.将从配置表中读取到的配置信息封装为一个配置实体类对象  jsonStr->实体类对象
        SingleOutputStreamOperator<TableProcess> tableProcessDS = mySqlStrDS.map(
            new MapFunction<String, TableProcess>() {
                @Override
                public TableProcess map(String jsonStr) throws Exception {
                    //为了处理方便，将jsonStr转换为jsonObj
                    JSONObject jsonObj = JSON.parseObject(jsonStr);
                    //获取对配置表的操作类型
                    String op = jsonObj.getString("op");
                    TableProcess tableProcess = null;
                    if ("d".equals(op)) {
                        tableProcess = jsonObj.getObject("before", TableProcess.class);
                    } else {
                        tableProcess = jsonObj.getObject("after", TableProcess.class);
                    }
                    tableProcess.setOp(op);
                    return tableProcess;
                }
            }
        );
        // tableProcessDS.print(">>");
        //TODO 7.根据配置信息提前将hbase中的表创建(删除)出来
        tableProcessDS = tableProcessDS.process(
            new ProcessFunction<TableProcess, TableProcess>() {
                private Connection conn;
                @Override
                public void open(Configuration parameters) throws Exception {
                    conn = HbaseUtil.getHbaseConnection();
                }

                @Override
                public void close() throws Exception {
                    HbaseUtil.closeHbaseConnection(conn);
                }

                @Override
                public void processElement(TableProcess tableProcess, Context ctx, Collector<TableProcess> out) throws Exception {
                    //获取对配置表进行的操作的类型
                    String op = tableProcess.getOp();
                    //根据对配置表的操作类型  到hbase中建表或者删表
                    String sinkTable = tableProcess.getSinkTable();
                    String[] families = tableProcess.getSinkFamily().split(",");

                    if("r".equals(op)||"c".equals(op)){
                        //建表
                        HbaseUtil.createHbaseTable(conn, GmallConfig.HBASE_NAMESPACE,sinkTable,families);
                    }else if("u".equals(op)){
                        //先删表
                        HbaseUtil.dropHbaseTable(conn,GmallConfig.HBASE_NAMESPACE,sinkTable);
                        //再建表
                        HbaseUtil.createHbaseTable(conn, GmallConfig.HBASE_NAMESPACE,sinkTable,families);
                    }else{
                        //删表
                        HbaseUtil.dropHbaseTable(conn,GmallConfig.HBASE_NAMESPACE,sinkTable);
                    }
                    out.collect(tableProcess);
                }
            }
        );
        //TODO 8.将配置流进行广播
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
            = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);
        BroadcastStream<TableProcess> broadcastDS = tableProcessDS.broadcast(mapStateDescriptor);

        //TODO 9.将主流和广播流进行关联
        BroadcastConnectedStream<JSONObject, TableProcess> connectDS = jsonObjDS.connect(broadcastDS);

        //TODO 10.对关联之后的数据进行处理
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
            new TableProcessFunction(mapStateDescriptor)
        );
        //TODO 11.将维度数据写到hbase对应的表中
        dimDS.print(">>>");
        dimDS.addSink(
            new DimSinkFunction()
        );


        env.execute();
    }
}